﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Linq;

namespace LaserTubeCuttingMachine.Utilities
{
    public class CollectionHelper
    {
        /// <summary>
        /// Pick up a property from a object, and collect the property value coming from the object list into a new list.
        /// </summary>
        /// <typeparam name="T1">Property type in object.</typeparam>
        /// <typeparam name="T2">Object type.</typeparam>
        /// <param name="sourceList">Object list.</param>
        /// <param name="eleName">Property name.</param>
        /// <returns>Property value list.</returns>
        /// <exception cref="ArgumentException">When sourceList is null or dose not have the property name.</exception>
        public static List<T1> GetElementsByName<T1, T2>(List<T2> sourceList, string eleName)
            where T2 : class
        {
            if (sourceList == null)
            {
                throw new ArgumentException($"'{nameof(sourceList)}' cannot be null.", nameof(sourceList));
            }

            Type t2 = typeof(T2);
            PropertyInfo? property = t2.GetProperty(eleName) ?? 
                throw new ArgumentException($"'{nameof(sourceList)}' has no Property {nameof(eleName)}.");
            
            List<T1> list = new List<T1>();

            foreach (T2 item in sourceList)
            {
                object? itemVal = property.GetValue(item);
                T1? ele;
                if (itemVal == null) continue;
                else ele = (T1)itemVal;

                list.Add(ele);
            }

            return list;
        } 

        /// <summary>
        /// Sometimes you need repetitive words, and only some words should be replaced.
        /// </summary>
        /// <param name="sourceList">Replacing words</param>
        /// <param name="template">The words unit template for generating repetitive words. 
        /// These words should contain placeholder to be replaced, like `placeholder`.</param>
        /// <returns>Generated repetitive words.</returns>
        /// <exception cref="ArgumentException">When sourceList is null.</exception>
        public static string CreateRepetitiveWordsWithList(List<string> sourceList, string template)
        {
            if (sourceList == null)
            {
                throw new ArgumentException($"'{nameof(sourceList)}' cannot be null.", nameof(sourceList));
            }

            StringBuilder sb = new StringBuilder();

            foreach (string s in sourceList)
            {
                sb.Append(template.Replace("`placeholder`", s));
            }

            return sb.ToString();
        }
    }
}
